<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 微信登陆控制器
 */
class Ucenter extends Base_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
        session_start();
    }
    public function checkUserLogin()
    {
        if(!isset($_SESSION)) session_start();
        if (isset($_SESSION['uid'])) {
            $this->load->model('redis_model');
            $redis = $this->redis_model->getRedisInstance();
            $redis->multi();
            //统计日活
            $k = date('Ymd',time());
            $redis->setBit('commlogin:'.$k,$_SESSION['uid'],1);
            //初次登陆
            $redis->getBit('commfirst',$_SESSION['uid']);
            $redis->setBit('commfirst',$_SESSION['uid'],1);
            //设置token
//            $appid = $this->input->get('appid');
//            $token = md5(substr($appid,0,4).'|'.substr($appid,8,4).'&'.$_SESSION['uid']);
//            $redis->set('commtoken:'.$_SESSION['uid'],$token);
            $data = $redis->exec();
            $res['uid']=$_SESSION['uid'];
            $res['wx_openid']=$_SESSION['wx_openid'];
            $res['isfirst']=$data[1];
//            $res['token']=$token;

            $this->success($res);
        }
        else $this->error('user does not login');
    }

    public function weixinlogin()
    {
        $get = $this->input->get();
        $param = '';
    	if(isset($get['pid'])&&is_numeric($get['pid'])) $param.=$get['pid'];
    	if(isset($get['page'])) $param.='-'.$get['page'];
    	if(isset($get['param'])) $param.='-'.$get['param'];

    	$scope='snsapi_base';
    	$redirect_uri = site_url('/ucenter/weixinlogincallback');
    	$this->load->library('openlogin/wechat');
        $this->wechat->set_scope($scope);
        $this->wechat->set_redirect_uri($redirect_uri);
        $this->wechat->set_state($param);
    	//跳转到引导页，静默授权
    	$this->wechat->get_code();	
    }
    
    public function weixinlogincallback()
    {
        $get = $this->input->get();
        if(isset($get['state'])) $param = $get['state'];
        else $param = '';

    	//获取openid
    	$this->load->library('openlogin/wechat');
    	$this->wechat->get_access_token();
    	$openid=$this->wechat->get_openid();
    	//检查用户是否已经注册
    	//$res=$this->user_model->getUser(array('wx_openid'=>$openid),'uid');
        $uid=$this->user_model->getUidByWxopenid($openid);
    	if($uid !== false){
    		//设置登陆session
    		if(!isset($_SESSION)) session_start();
    		$_SESSION['uid'] = $uid;
//    		$_SESSION['is_login'] = 1;
    		$_SESSION['wx_openid'] = $openid;
    		//跳转网页
            if (!empty($param)){
                $suffix = '';
                $param = explode('-',$param);
                $pid = (int)$param[0];
                $suffix .= isset($param[1])&&!empty($param[1])?'#page/'.$param[1].'.html':'';
                if (isset($param[2])&&!empty($param[2])){
                    $pparam = explode('.',$param[2]);
                    $suffix .= isset($pparam[1])&&!empty($pparam[1])?'?'.$pparam[0].'='.$pparam[1]:'';
                }

                $this->load->model('redis_model');
                $redis = $this->redis_model->getRedisInstance();
                $url = $redis->get('redirect:'.$pid);
                if ($url !== false) redirect($url.$suffix);
                else die('page does not found');
            }
    	}
    	//没有注册，获取用户基本信息
    	else{
    		$this->firstweixinlogin($param);
    	}
    }

    //第一次登陆
    public function firstweixinlogin($param = "")
    {
        $redirect_uri=site_url('/ucenter/firstlogincallback');
        $scope='snsapi_userinfo';
        $this->wechat->set_scope($scope);
        $this->wechat->set_state($param);
        $this->wechat->set_redirect_uri($redirect_uri);
        //跳转到引导页，授权登陆
        $this->wechat->get_code();
    }
    
    public function firstlogincallback()
    {
        $get = $this->input->get();
        if(isset($get['state'])) $param = $get['state'];
        else $param = '';
    	
    	$this->load->library('openlogin/wechat');
    	$this->wechat->get_access_token();
    	$info=$this->wechat->get_user_info();
    	//检查用户是否已经注册
    	$res=$this->user_model->getUser(array('wx_unionid'=>$info['unionid']),'uid');
    	    	
    	if($info!==false){
    	    if (empty($res)){
                //新用户注册
                $data = array(
                    'utype'      => 'weixin',
                    'wx_openid'  => $info['openid'],
                    'wx_unionid' => $info['unionid'],
                    'userName'   => $info['nickname'],
                    'userToken'  => md5($info['access_token']),
                    'userIcon'   => $info['userIcon'],
                    'status'     => 1,
                    'created'    => time(),
                    'changed'    => time()
                );
                $uid = $this->user_model->createUser($data);
                if($uid){
                    $this->user_model->createUserInfo(array('uid' => $uid, 'userGender'=>$info['gender']));

                    $this->load->model('redis_model');
                    $redis = $this->redis_model->getRedisInstance();
                    $redis->multi();
                    //设置登陆信息
                    $redis->set('user:'.$info['openid'],$uid);
                    //新用户赠送100能量豆
                    $redis->incrby('user:'.$uid.'.beans',100);
                    $redis->exec();
                    
                    //设置登陆session
                    if(!isset($_SESSION)) session_start();
                    $_SESSION['uid'] = $uid;
//                    $_SESSION['is_login'] = 1;
                    $_SESSION['wx_openid'] = $info['openid'];
                    //跳转网页
                    if (!empty($param)){
                        $suffix = '';
                        $param = explode('-',$param);
                        $pid = $param[0];
                        $suffix .= isset($param[1])&&!empty($param[1])?'#page/'.$param[1].'.html':'';
                        if (isset($param[2])&&!empty($param[2])){
                            $pparam = explode('.',$param[2]);
                            $suffix .= isset($pparam[1])&&!empty($pparam[1])?'?'.$pparam[0].'='.$pparam[1]:'';
                        }

                        $url = $redis->get('redirect:'.$pid);
                        if ($url !== false) redirect($url.$suffix);
                        else die('page does not found');
                    }
                }else{die("系统错误，请重试");}
            }else{
    	        //用户存在
                $data = array(
                    'utype'      => 'weixin',
                    'wx_openid'  => $info['openid'],
                    'wx_unionid' => $info['unionid'],
                    'userName'   => $info['nickname'],
                    'userToken'  => md5($info['access_token']),
                    'userIcon'   => $info['userIcon']
                );
                $this->user_model->editUser($data,array('uid'=>$res['uid']));
                $this->user_model->setUidWithOpenid($info['openid'],$res['uid']);
                //设置登陆session
                if(!isset($_SESSION)) session_start();
                $_SESSION['uid'] = $res['uid'];
//                    $_SESSION['is_login'] = 1;
                $_SESSION['wx_openid'] = $info['openid'];
                //跳转网页
                if (!empty($param)){
                    $suffix = '';
                    $param = explode('-',$param);
                    $pid = $param[0];
                    $suffix .= isset($param[1])&&!empty($param[1])?'#page/'.$param[1].'.html':'';
                    if (isset($param[2])&&!empty($param[2])){
                        $pparam = explode('.',$param[2]);
                        $suffix .= isset($pparam[1])&&!empty($pparam[1])?'?'.$pparam[0].'='.$pparam[1]:'';
                    }
                    $this->load->model('redis_model');
                    $redis = $this->redis_model->getRedisInstance();
                    $url = $redis->get('redirect:'.$pid);
                    if ($url !== false) redirect($url.$suffix);
                    else die('page does not found');
                }
            }
    	}else{die("系统错误，请重试");}
    } 
    /**
     * 退出
     */
    public function logout()
    {
        $this->load->helper('cookie');
        $this->load->helper('url');
        if (!isset($_SESSION)) session_start();
        $_SESSION = null;
        if (isset($_COOKIE[session_name()])){
            set_cookie(session_name(),'',time()-3600);
        }
        session_destroy();
        redirect(site_url('admin/adminlogin'));
    }

}
